package com.angis.fx.activity.jcdj;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.UUID;

import org.xmlpull.v1.XmlPullParserException;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.BroadcastReceiver;
import android.content.ContentValues;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.database.Cursor;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CheckedTextView;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemSelectedListener;

import com.angis.fx.activity.Enforcement;
import com.angis.fx.activity.R;
import com.angis.fx.activity.login.LoginActivity;
import com.angis.fx.activity.service.CheckDutyService;
import com.angis.fx.activity.sxry.SxryActivity;
import com.angis.fx.activity.sxry.SxryMActivity;
import com.angis.fx.activity.zdcf.AttendanceActivity;
import com.angis.fx.adapter.MultipleAdapter;
import com.angis.fx.adapter.MultipleAdapter.ViewHolder;
import com.angis.fx.data.DraftInfo;
import com.angis.fx.db.CheckDraftDBHelper;
import com.angis.fx.db.QuickTextDBHelper;
import com.angis.fx.db.ZCTypeDBHelper;
import com.angis.fx.util.CommonUtil;
import com.angis.fx.util.ContentValuesUtil;
import com.angis.fx.util.SpinnerUtil;

public class NoCedulaCheckActivity extends Activity {

	
	private EditText mPlacenameEt;
	private Spinner mPlaceTypeSp;
	private Spinner mAreaSp1;
	private Spinner mAreaSp2;
	private EditText mPrincipalEt;
	private EditText mAddressEt;
	private Spinner mCheckResultSp;
	private EditText mQuickTextEt;
	private Spinner mCheckSituationSp;
	private EditText mArrivalDateEt;
	private EditText mLeaveDateEt;
	
	private Button mQuickTextBt;
	private Button mArrivalDateBt;
	private Button mLeaveDateBt;
	private Button mEditBt;
	private Button mReturnBt;
	private Button ncc_upload_pic_bt;
	
	private MultipleAdapter mMultipleDialogListAdapter;
	private CheckedTextView mCheckTextView;
	private Set<Integer> mPos;
	private Intent mIntent;
	private String mId;
	private UpdateReceiver mUpdateReceiver;
	private boolean isSave=false;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.nocedulacheckactivity);
		initActivity();
		initValues();
		mQuickTextBt.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				mIntent = new Intent();
				mPos = new HashSet<Integer>();
				LayoutInflater layoutInflater = LayoutInflater.from(NoCedulaCheckActivity.this);
				final View lView = layoutInflater.inflate(R.layout.multiple_dialog, null);
				ListView mListView = (ListView)lView.findViewById(R.id.multiple_dialoglist);
				mMultipleDialogListAdapter = new MultipleAdapter(NoCedulaCheckActivity.this);
				List<String> lDataList = new ArrayList<String>();
				QuickTextDBHelper lDBHelper = new QuickTextDBHelper(NoCedulaCheckActivity.this);
				Cursor lCursor = lDBHelper.getAllQuickText();
				if(lCursor.getCount() > 0) {
					if(lCursor.moveToFirst()) {
						do {
							lDataList.add(lCursor.getString(1));
						} while (lCursor.moveToNext());
					}
				}
				lCursor.close();
				lDBHelper.closeDB();
				initMultipleDialog(mListView, lDataList);
		        new AlertDialog.Builder(NoCedulaCheckActivity.this)
					.setTitle("快速文本")
					.setView(lView)
					.setPositiveButton(R.string.confirm,
							new DialogInterface.OnClickListener() {
								public void onClick(DialogInterface dialog,
										int whichButton) {
									StringBuffer lSb = new StringBuffer();
									for (Integer pos : mPos) {
										ViewHolder lHodler = (ViewHolder) mMultipleDialogListAdapter.getView(pos, null, null).getTag();
										lSb.append(lHodler.getName().getText().toString()).append(";");
									}
									mQuickTextEt.setText(mQuickTextEt.getText().toString() + lSb.toString());
								}
							})
					.setNegativeButton(R.string.cancel,
							new DialogInterface.OnClickListener() {
								public void onClick(DialogInterface dialog,
										int whichButton) {
									dialog.cancel();
								}
							}).create().show();
			}
		});
		mArrivalDateBt.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				mIntent = new Intent();
				Bundle lBundle = new Bundle();
				lBundle.putInt("RESULTCODE", 1);
				mIntent.putExtras(lBundle);
				mIntent.setClass(NoCedulaCheckActivity.this, AttendanceActivity.class);
				NoCedulaCheckActivity.this.startActivityForResult(mIntent, 1);
			}
		});
		mLeaveDateBt.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				mIntent = new Intent();
				Bundle lBundle = new Bundle();
				lBundle.putInt("RESULTCODE", 2);
				mIntent.putExtras(lBundle);
				mIntent.setClass(NoCedulaCheckActivity.this, AttendanceActivity.class);
				NoCedulaCheckActivity.this.startActivityForResult(mIntent, 1);
			}
		});
		mCheckResultSp.setOnItemSelectedListener(new OnItemSelectedListener() {

			@Override
			public void onItemSelected(AdapterView<?> arg0, View arg1,
					int arg2, long arg3) {
				String lSelected = ((TextView)mCheckResultSp.getSelectedView()).getText().toString();
				mPos = new HashSet<Integer>();
				List<String> lDataList = new ArrayList<String>();
				if("正常" != lSelected) {
					if(!"其他".equals(lSelected)) {
						Bundle lBundle = new Bundle();
						Intent lIntent = new Intent();
						lBundle.putInt("RESULTCODE", 3);
						lBundle.putString("type", ((TextView)mPlaceTypeSp.getSelectedView()).getText().toString());
						lIntent.putExtras(lBundle);
						lIntent.setClass(NoCedulaCheckActivity.this, MultipleDialogActivity.class);
						NoCedulaCheckActivity.this.startActivityForResult(lIntent, lBundle.getInt("RESULTCODE"));
					}else {
						mMultipleDialogListAdapter = new MultipleAdapter(NoCedulaCheckActivity.this);
						LayoutInflater lLayoutInflater = LayoutInflater.from(NoCedulaCheckActivity.this);
						View lView = lLayoutInflater.inflate(R.layout.multiple_dialog, null);
						ListView mListView = (ListView)lView.findViewById(R.id.multiple_dialoglist);
						ZCTypeDBHelper lDBHelper2 = new ZCTypeDBHelper(NoCedulaCheckActivity.this);
						Cursor lCursor = lDBHelper2.getZCTypeByConditionType(((TextView)mPlaceTypeSp.getSelectedView()).getText().toString());
						if(lCursor.moveToFirst()) {
							do {
								String type = lCursor.getString(2);
								lDataList.add(type);
							} while (lCursor.moveToNext());
						}
						lCursor.close();
						lDBHelper2.closeDB();
						initMultipleDialog(mListView, lDataList);
						new AlertDialog.Builder(NoCedulaCheckActivity.this)
							.setTitle(lSelected)
							.setView(lView)
							.setPositiveButton(R.string.confirm,
									new DialogInterface.OnClickListener() {
										public void onClick(DialogInterface dialog,
												int whichButton) {
											StringBuffer lSb = new StringBuffer();
											for (Integer pos : mPos) {
												ViewHolder lHodler = (ViewHolder) mMultipleDialogListAdapter.getView(pos, null, null).getTag();
												lSb.append(lHodler.getName().getText().toString()).append("&");
											}
											mQuickTextEt.setText(lSb.toString());
										}
									})
							.setNegativeButton(R.string.cancel,
									new DialogInterface.OnClickListener() {
										public void onClick(DialogInterface dialog,
												int whichButton) {
											dialog.cancel();
										}
								}).create().show();
					}
					
				}
			}

			@Override
			public void onNothingSelected(AdapterView<?> arg0) {
				//mCheckResultSp.setSelection(0);
			}
		});
		mEditBt.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				try {
					DraftInfo lDraftInfo = initCheckDraft();
					if(null != lDraftInfo) {
						CheckDraftDBHelper lDBHelper = new CheckDraftDBHelper(NoCedulaCheckActivity.this);
						ContentValues lValues = ContentValuesUtil.convertCheckDraft(lDraftInfo);
						lDBHelper.insert(lValues);
						lDBHelper.closeDB();
						mEditBt.setEnabled(false);
						Toast.makeText(NoCedulaCheckActivity.this, "保存草稿成功!", Toast.LENGTH_SHORT).show();
						isSave=true;
					}
				} catch (Exception e) {
					Toast.makeText(NoCedulaCheckActivity.this, "保存草稿失败!", Toast.LENGTH_SHORT).show();
				}
			}
		});
		mReturnBt.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				mUpdateReceiver = new UpdateReceiver();
				IntentFilter lFilter = new IntentFilter();
				lFilter.addAction("upLoadResult");
				NoCedulaCheckActivity.this.registerReceiver(mUpdateReceiver, lFilter);
				
				mIntent = new Intent(NoCedulaCheckActivity.this, CheckDutyService.class);
				Bundle lBundle = new Bundle();
				lBundle.putBoolean("isSave", isSave);
				DraftInfo lDraftInfo = initCheckDraft();
				if(null != lDraftInfo) {
					lBundle.putSerializable("CHECKDUTY", lDraftInfo);
					mIntent.putExtras(lBundle);
					startService(mIntent);
				}
				
				
			}
		});
	}
	
	public class UpdateReceiver extends BroadcastReceiver{

		@Override
		public void onReceive(Context context, Intent intent) {
			NoCedulaCheckActivity.this.unregisterReceiver(mUpdateReceiver);
			boolean repupload = intent.getBooleanExtra("isCompleteUpload", false);
			if(repupload
					){
				mReturnBt.setEnabled(false);
    			mEditBt.setEnabled(false);
    			ncc_upload_pic_bt.setEnabled(true);
			}
//			if("0".equals(response)) {
//    			Toast.makeText(NoCedulaCheckActivity.this, "上传失败!", Toast.LENGTH_SHORT).show();
//    		}else if("-1".equals(response)) {
//    			Toast.makeText(NoCedulaCheckActivity.this, "服务器连接错误!", Toast.LENGTH_SHORT).show();
//    		}else if("1".equals(response)) {
//    			mReturnBt.setEnabled(false);
//    			mEditBt.setEnabled(false);
//    			Toast.makeText(NoCedulaCheckActivity.this, "上传成功!", Toast.LENGTH_SHORT).show();
//    		}
		}
		
	}
	
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		if(null != data && null != data.getExtras()) {
			Bundle lBundle = data.getExtras();
			String lDatetime = lBundle.getString("DATATIME");
			String jcjg = lBundle.getString("JCJG");
			SimpleDateFormat lSdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			switch (resultCode){  
			case 1:  
	        	try {
	        		String tempDatetime = mArrivalDateEt.getText().toString();
	        		mArrivalDateEt.setText(lDatetime);
	        		if(lSdf.parse(mArrivalDateEt.getText().toString())
	        				.compareTo(lSdf.parse(lSdf.format(Enforcement.mStartdutytime))) < 0){
	        			mArrivalDateEt.setText(tempDatetime);
	        			Toast.makeText(NoCedulaCheckActivity.this, "到达时间比开始时间早,请重新选择!", Toast.LENGTH_LONG).show();
	        			return;
	        		}
				} catch (Exception e) {
				}
	            break;
	        case 2:
	        	try {
	        		String tempDatetime = mLeaveDateEt.getText().toString();
	        		mLeaveDateEt.setText(lDatetime);
	        		if(mArrivalDateEt.getText().toString().length() > 0) {
		        		if(lSdf.parse(mArrivalDateEt.getText().toString()).compareTo(lSdf.parse(lDatetime)) > 0) {
		        			mLeaveDateEt.setText(tempDatetime);
		        			Toast.makeText(NoCedulaCheckActivity.this, "离开时间比到达时间早,请重新选择!", Toast.LENGTH_LONG).show();
		        		}else {
		        			mLeaveDateEt.setText(lDatetime);
		        		}
	        		}else {
	        			mLeaveDateEt.setText(tempDatetime);
	        			Toast.makeText(NoCedulaCheckActivity.this, "请先选择到达时间!", Toast.LENGTH_LONG).show();
	        		}
				} catch (Exception e) {
				}
	        	break;
		        case 3:
		        	mQuickTextEt.setText(jcjg);
		        	break;
			}  
		}
	}
	
	private DraftInfo initCheckDraft() {
		if(mQuickTextEt.getText().toString().length() < 1) {
			Toast.makeText(NoCedulaCheckActivity.this, "检查情况不能为空!", Toast.LENGTH_SHORT).show();
			return null;
		}
		if(mArrivalDateEt.getText().toString().length() < 1) {
			Toast.makeText(NoCedulaCheckActivity.this, "到达时间不能为空!", Toast.LENGTH_SHORT).show();
			return null;
		}
		if(mLeaveDateEt.getText().toString().length() < 1) {
			Toast.makeText(NoCedulaCheckActivity.this, "离开时间不能为空!", Toast.LENGTH_SHORT).show();
			return null;
		}
		if(mPrincipalEt.getText().toString().length() < 1) {
			Toast.makeText(NoCedulaCheckActivity.this, "负责人不能为空!", Toast.LENGTH_SHORT).show();
			return null;
		}
		if(mAddressEt.getText().toString().length() < 1) {
			Toast.makeText(NoCedulaCheckActivity.this, "场所地址不能为空!", Toast.LENGTH_SHORT).show();
			return null;
		}
		if(mPlacenameEt.getText().toString().length() < 1) {
			Toast.makeText(NoCedulaCheckActivity.this, "场所名称不能为空!", Toast.LENGTH_SHORT).show();
			return null;
		}
		if(mId==null || mId.equals("")){
			mId = UUID.randomUUID().toString();}
		
		DraftInfo lDraftInfo = new DraftInfo(
				mId,
				"",
				mPlacenameEt.getText().toString(),
				mAddressEt.getText().toString(),
				mPrincipalEt.getText().toString(),
				((TextView)mPlaceTypeSp.getSelectedView()).getText().toString(),
				"",
				"",
				((TextView)mAreaSp2.getSelectedView()).getText().toString(),
				"",
				"",
				"",
				"",
				"",
				"",
				getCurrentJcjp(),
				CommonUtil.getCurrentDate(),
				mQuickTextEt.getText().toString(),
				mQuickTextEt.getText().toString(),
				SxryMActivity.SXRP_SELECT_MEMBER.replaceAll(",", "|"),
				SxryActivity.QTRY_EDIT_MEMBER,
				CommonUtil.randomNumber(19),
				CommonUtil.randomUUID(),
				"2",
				LoginActivity.g_username,
				mArrivalDateEt.getText().toString(),
				mLeaveDateEt.getText().toString(),
				Enforcement.mDutyno,
				getDjguid(),
				((TextView)mCheckSituationSp.getSelectedView()).getText().toString(),
				(SxryMActivity.SXRP_SELECT_MEMBER.split(",").length + SxryActivity.QTRY_EDIT_MEMBER_COUNT) + "",
				((TextView)mAreaSp2.getSelectedView()).getText().toString(),
				"0",
				"",
				"",
				"",
				"",
				"",
				getCheckTime());
		return lDraftInfo;
	}
	
	private String getDjguid() {
		String lDjguid = ((TextView)mCheckSituationSp.getSelectedView()).getText().toString();
		if("明察".equals(lDjguid)) {
			return Enforcement.mMcTJGuid;
		}else {
			return Enforcement.mAfTJGuid;
		}
	}
	
	private String getCheckTime() {
		try {
			String date1 = getString(R.id.dc_arrivaldate_et);
			String date2 = getString(R.id.dc_leavedate_et);
			return date1.split(" ")[1].substring(0,date1.split(" ")[1].lastIndexOf(":")) + "-" + date2.split(" ")[1].substring(0,date2.split(" ")[1].lastIndexOf(":"));
		} catch (Exception e) {
			return "";
		}
	}

	private String getCurrentJcjp() {
		String lStr = getString(R.id.dc_checkresult_sp);
		if("正常".equals(lStr)) {
			return "0";
		}else if("其他".equals(lStr)) {
			return "1";
		}else if("违规".equals(lStr)) {
			return "2";
		}else {
			return "0";
		}
	}
	
	private void initMultipleDialog(ListView mListView,
			List<String> lDataList) {
		mMultipleDialogListAdapter.setData(lDataList, mPos);
		mListView.setAdapter(mMultipleDialogListAdapter);
        mListView.setOnItemClickListener(new OnItemClickListener(){
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				mCheckTextView = (CheckedTextView) view.findViewById(R.id.multiple_dialog_item_ctv);
				if(mCheckTextView.isChecked()){
					mPos.remove(position);
					mCheckTextView.setChecked(false);
				}else if(!mCheckTextView.isChecked()){
					mPos.add(position);
					mCheckTextView.setChecked(true);
				}
			}
        });
	}
	
	private void initValues() {
		ArrayAdapter<String> lAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item);
		lAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		lAdapter.add("正常");
		lAdapter.add("其他");
		lAdapter.add("违规");
		mCheckResultSp.setAdapter(lAdapter);
		lAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item);
		lAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		lAdapter.add("明查");
		lAdapter.add("暗访");
		mCheckSituationSp.setAdapter(lAdapter);
		try {
			SpinnerUtil.setAreaCodes(this,(Spinner) findViewById(R.id.ncc_area_sp1));
			mAreaSp1.setOnItemSelectedListener(new OnItemSelectedListener() {

				@Override
				public void onItemSelected(AdapterView<?> arg0, View arg1,
						int arg2, long arg3) {
					SpinnerUtil.setChildAreaCodes(NoCedulaCheckActivity.this, mAreaSp2, mAreaSp1.getSelectedItem().toString());
				}

				@Override
				public void onNothingSelected(AdapterView<?> arg0) {
					SpinnerUtil.setChildAreaCodes(NoCedulaCheckActivity.this, mAreaSp2, "");
					
				}
			});
			SpinnerUtil.setChangsuoType(this, (Spinner) findViewById(R.id.ncc_placetype_sp));
		} catch (XmlPullParserException e) {
			Toast.makeText(this, "配置文件读取错误", Toast.LENGTH_LONG);
		} catch (IOException e) {
			Toast.makeText(this, "配置文件读取错误", Toast.LENGTH_LONG);
		}
		ncc_upload_pic_bt.setEnabled(false);
	}

	private void initActivity() {
		mPlacenameEt = (EditText) findViewById(R.id.ncc_placename_et);
		mPlaceTypeSp = (Spinner) findViewById(R.id.ncc_placetype_sp);
		mAreaSp1 = (Spinner) findViewById(R.id.ncc_area_sp1);
		mAreaSp2 = (Spinner) findViewById(R.id.ncc_area_sp2);
		mPrincipalEt = (EditText) findViewById(R.id.ncc_principal_et);
		mAddressEt = (EditText) findViewById(R.id.ncc_address_et);
		mQuickTextEt = (EditText) findViewById(R.id.ncc_quicktext_et);
		mCheckResultSp = (Spinner) findViewById(R.id.ncc_checkresult_sp);
		mCheckSituationSp = (Spinner) findViewById(R.id.ncc_checksituation_sp);
		mArrivalDateEt = (EditText) findViewById(R.id.ncc_arrivaldate_et);
		mArrivalDateEt.setEnabled(false);
		mLeaveDateEt = (EditText) findViewById(R.id.ncc_leavedate_et);
		mLeaveDateEt.setEnabled(false);
		
		mQuickTextBt = (Button) findViewById(R.id.ncc_quicktext_bt);
		mArrivalDateBt = (Button) findViewById(R.id.ncc_arrivaldate_bt);
		mLeaveDateBt = (Button) findViewById(R.id.ncc_leavedate_bt);
		mEditBt = (Button) findViewById(R.id.ncc_savedraft_bt);
		mReturnBt = (Button) findViewById(R.id.ncc_upload_bt);
		ncc_upload_pic_bt=(Button)findViewById(R.id.ncc_upload_pic_bt);
	}

}
